package com.sky.task;

import cn.hutool.core.collection.CollUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrdersMapper orderMapper;

    // 每分钟检查一次，如果订单状态为待支付，且支付时间超过15分钟，则自动取消订单
    @Scheduled(cron = "0 0/1 * * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processTimeOutOrder() {
        log.info("清理超时订单开始...");
        //1. 查询超时订单
        // select * from orders where status = 1 and checkoutTime < 当前时间-15分钟
        LocalDateTime old15Now = LocalDateTime.now().minusMinutes(15);
        List<Orders> list = orderMapper.findByStatusAndOrderTime(1,old15Now);
        //2. 如果有，修改订单状态为已取消
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(orders -> {
                orders.setStatus(6);// 订单状态：已取消
                orders.setCancelReason("订单超时未支付");// 取消原因
                orders.setCancelTime(LocalDateTime.now());// 取消时间
                orderMapper.update(orders);
            });
        }

        log.info("清理超时订单结束...");

    }


    // 每天凌晨1点，将派送中订单状态改为已完成
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateDeliveryStatus() {
        log.info("派送中订单改为已完成开始...");
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime lastday = LocalDateTime.now().minusHours(1);
        List<Orders> list = orderMapper.findByStatusAndOrderTime(4,lastday);
        //2. 如果有，修改订单状态为已完成
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(orders -> {
                orders.setStatus(5);// 订单状态：已完成
                orderMapper.update(orders);
            });
        }
        log.info("派送中订单改为已完成结束...");
    }

}
